import { Mic, MicOff } from 'lucide-react'
import { TaskButton } from '@/components/common/TaskButton'
import { useAIAssist } from '@/hooks/useAIAssist'
import { useAutoReply } from '@/hooks/useAutoReply'
import { useCurrentLiveControl } from '@/hooks/useLiveControl'
import { useToast } from '@/hooks/useToast'

export default function BroadcastControl() {
  const { isBroadcasting, setIsBroadcasting, config } = useAIAssist()
  const { isListening } = useAutoReply()
  const isConnected = useCurrentLiveControl(context => context.isConnected)
  const platform = useCurrentLiveControl(context => context.platform)
  const { toast } = useToast()

  const isTaskForbidden = platform !== 'douyin' && platform !== 'buyin'

  const handleBroadcastToggle = async () => {
    // ✅ 修复: 根据厂商检查对应的配置
    const provider = config.provider || 'aliyun'
    
    if (provider === 'aliyun') {
      if (!config.aliyun.accessKeyId || !config.aliyun.accessKeySecret || !config.aliyun.appKey) {
        toast.error('请先配置阿里云 API')
        return
      }
    } else if (provider === 'tencent') {
      if (!config.tencent?.secretId || !config.tencent?.secretKey) {
        toast.error('请先配置腾讯云 API')
        return
      }
    }

    try {
      setIsBroadcasting(!isBroadcasting)
      if (!isBroadcasting) {
        toast.success('AI 助播已启动')
      } else {
        toast.success('AI 助播已停止')
      }
    } catch (error) {
      console.error('切换 AI 助播失败:', error)
      toast.error('操作失败')
    }
  }

  return (
    <div className="flex items-center justify-between">
      <div className="flex items-center gap-4">
        {/* 监听状态 */}
        <div className="flex items-center gap-2">
          <div
            className={`w-2.5 h-2.5 rounded-full ${
              isListening === 'listening'
                ? 'bg-green-500 animate-pulse'
                : 'bg-gray-300'
            }`}
          />
          <span className="text-sm text-muted-foreground">
            {isListening === 'listening' ? '正在监听评论' : '未监听评论'}
          </span>
        </div>
        {/* 播报状态 */}
        <div className="flex items-center gap-2">
          {isBroadcasting ? (
            <Mic className="w-4 h-4 text-green-500" />
          ) : (
            <MicOff className="w-4 h-4 text-gray-400" />
          )}
          <span className="text-sm text-muted-foreground">
            {isBroadcasting ? 'AI助播运行中' : 'AI助播已停止'}
          </span>
        </div>
      </div>

      <div className="flex items-center gap-2">
        {/* 任务启动按钮 */}
        <TaskButton
          isTaskRunning={isBroadcasting}
          onStartStop={handleBroadcastToggle}
          forbidden={isTaskForbidden}
        />
      </div>
    </div>
  )
}

